import { ColumnProps } from 'antd/lib/table';

import { Tag, Row, Spin, Table, Switch } from 'antd';

import React from 'react';
import { NewProductRecommend } from '../model';
import { ListTableContext, List } from '..';

const columns: ColumnProps<NewProductRecommend>[] = [
  {
    title: '编号',
    dataIndex: 'id',
    align: 'center',
  },
  {
    title: '商品名称',
    dataIndex: 'productName',
    align: 'center',
  },
  {
    title: '是否推荐',
    dataIndex: 'recommendStatus',
    align: 'center',
    render: (value, record) => (
      <ListTableContext.Consumer>
        {list => (
          <Switch
            defaultChecked={value === 1}
            onChange={checkedValue =>
              list.onSwitchChange({ ...record, recommendStatus: checkedValue ? 1 : 0 })
            }
          />
        )}
      </ListTableContext.Consumer>
    ),
  },
  {
    title: '排序',
    dataIndex: 'sort',
    align: 'center',
    render: text => text || 0,
  },
  {
    title: '状态',
    key: 'status',
    align: 'center',
    render: (_text, record) => {
      const color = record.recommendStatus === 1 ? 'green' : 'orange';
      const text = record.recommendStatus === 1 ? '推荐中' : '未推荐';
      return <Tag color={color}>{text}</Tag>;
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: '170px',
    align: 'center',
    render: (_text, record) => (
      <ListTableContext.Consumer>
        {(list: List) => (
          <div className="horizon-button-group">
            <a href="#">设置排序</a>
            <a
              href="#"
              onClick={e => {
                e.preventDefault();
                list.onRowRemove(record.id);
              }}
            >
              移除
            </a>
          </div>
        )}
      </ListTableContext.Consumer>
    ),
  },
];

export interface TableProps {
  recommends: NewProductRecommend[];
  loading?: boolean;
}

export default (props => (
  <Row>
    <Spin spinning={props.loading}>
      <Table<NewProductRecommend>
        dataSource={props.recommends}
        columns={columns}
        rowKey="id"
        bordered
      />
    </Spin>
  </Row>
)) as React.FC<TableProps>;
